package _go

import (
	"context"
	"fmt"
	"gitee.com/kmyss/gf-ex/ysbuild"
	"gitee.com/kmyss/gf-ex/yslog"
	"gitee.com/kmyss/gf-ex/ysother"
	"gitee.com/kmyss/gf-ex/ysutils"
	"gitee.com/kmyss/ys-cli/internal/consts"
	"gitee.com/kmyss/ys-cli/internal/model"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gcfg"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/os/gproc"
)

const (
	varMap = "gfcli.build.varMap"
)

// <in> 版本号
func (s *sGo) buildPath(ctx context.Context, in string) (out string) {
	return gfile.Join(consts.OutPath, in)
}

// <in> 配置文件名
func (s *sGo) tmpBuildCfgPath(ctx context.Context, in string) (out string) {
	return gfile.Join(consts.TmpPath, in+".yaml")
}

// 创建临时 配置文件
func (s *sGo) createTmpBuildCfg(ctx context.Context, in *model.GolangBuildInput) (err error) {
	_ = g.Cfg(in.BuildCfg).GetAdapter().(*gcfg.AdapterFile).Set(varMap, g.MapStrStr{
		ysbuild.AppNameKey: in.Name,
		ysbuild.VersionKey: in.Version,
		ysbuild.AuthorKey:  in.Author,
		ysbuild.RepoKey:    in.Repo,
	})

	err = ysother.WriteYamlConfig(ctx, consts.TmpPath, in.BuildCfg)
	if err != nil {
		return
	}

	return
}

func (s *sGo) clearTmpBuildCfg(ctx context.Context, in string) {
	_ = gfile.Remove(s.tmpBuildCfgPath(ctx, in))
}

func (s *sGo) doBuild(ctx context.Context, in *model.GolangBuildInput) (err error) {
	cmd := fmt.Sprintf("gf build --gf.gcfg.path=%s --gf.gcfg.file=%s -v %s", consts.TmpPath, in.BuildCfg, in.Version)
	if ysutils.IsDebugMode() {
		cmd += " --debug"
	}
	s.log().Debug(ctx, cmd)
	err = gproc.Shell(ctx, cmd, yslog.GetWriter(), nil)
	if err != nil {
		return
	}

	return
}
